'use strict'
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')
const app = new Koa()
const PORT = 7778
const cmd = require('node-cmd')

/* 处理错误 */
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    console.info(err)
    progress.exit(1)
  }
})
app.use(bodyParser())
const router = new Router()

router.post('/ark-graphql-server-p-tx-153', function(ctx, next) {
  let branch = ctx.request.body.ref
  if (branch == 'refs/heads/beta') {
    console.info('auto build ark-graphql-server on ' + branch + '...')
    cmd.get(
      `
      cd /home/ark-graphql-server
      git checkout
      git reset --hard origin/beta
      git clean -f
      sudo git pull origin beta
      cnpm i
      npm rebuild
      npm run build
      npm rebuild
      pm2 reload ark-graphql-server
      pm2 reload ark-task-server
      pm2 reload ark-queue-server
    `,
      function(err, data, stderr) {
        if (!err) {
          console.log(
            'the node-cmd cloned dir contains these files :\n\n',
            data
          )
        } else {
          console.log('error', err)
        }
      }
    )
    ctx.body = 'auto build ark-graphql-server on beta'
  }
})

router.post('/ark-graphql-server-p-tx-73', function(ctx, next) {
  let branch = ctx.request.body.ref
  if (branch == 'refs/heads/master') {
    console.info('auto build ark-graphql-server on ' + branch + '...')
    cmd.get(
      `
      cd /mj-graphql-server
      git checkout
      git reset --hard origin/master
      git clean -f
      sudo git pull origin master
      cnpm i
      npm rebuild
      npm run build
      npm rebuild
      pm2 reload ark-graphql-server
      pm2 reload ark-task-server
      pm2 reload ark-queue-server
    `,
      function(err, data, stderr) {
        if (!err) {
          console.log(
            'the node-cmd cloned dir contains these files :\n\n',
            data
          )
        } else {
          console.log('error', err)
        }
      }
    )
    ctx.body = 'auto build ark-graphql-server on master'
  }
})

app.use(router.routes()).use(router.allowedMethods())
app.listen(PORT, () => {
  console.log('auto build is listening on %s', PORT)
})
